<template>
  <div class="login">
    <van-nav-bar title="登录" />

    <van-cell-group @input="validate">
      <van-field
        v-model="mobile"
        required
        label="手机号"
        placeholder="请输入手机号"
        :error-message="mobileErrMsg"
      />
      <van-field
        v-model="code"
        center
        clearable
        required
        label="短信验证码"
        placeholder="请输入短信验证码"
        :error-message="codeErrMsg"
      >
        <template #button>
          <van-button size="small" type="primary" @click="sendCode">发送验证码</van-button>
        </template>
      </van-field>
    </van-cell-group>
    <div class="btn-wrap">
      <van-button type="info" @click="login">登录按钮</van-button>
      <van-button type="info" @click="getInfo">获取个人资料</van-button>
    </div>
  </div>

</template>
<script>
import { reqLogin, reqCode, reqGetUser } from '@/api/user'
export default {
  name: 'LoginIndex',
  data() {
    return {
      mobile: '15381441291',
      code: '246810',
      mobileErrMsg: '',
      codeErrMsg: ''
    }
  },
  methods: {
    async sendCode() {
      try {
        // const res = await this.$request.get('/v1_0/sms/codes/' + this.mobile)
        const res = await reqCode(this.mobile)
        console.log(res)
        this.$toast.success('验证码发送成功')
      } catch (e) {
        this.$toast.fail(e.response.data.message)
      }
    },
    async login() {
      if (!this.validate()) return
      this.$toast.loading({
        duration: 0,
        overlay: true,
        message: '登陆中...',
        forbidClick: true
      })
      try {
        const res = await reqLogin(this.mobile, this.code)
        console.log(res.data)
        this.$toast.success('登录成功')
        this.$store.commit('user/setTokenInfo', res.data)
        this.$router.push(this.$route.query.backto || '/')
      } catch (err) { this.$toast.err.data.message }
    },
    async getInfo() {
      const res = await reqGetUser()
      console.log(res)
    },
    // 表单验证=================
    validate() {
      if (this.mobile === '') {
        this.mobileErrMsg = '请输入正确手机号'
        return false
      }
      if (!/^1[3-8]\d{9}$/.test(this.mobile)) {
        this.mobileErrMsg = '请输入正确手机号'
        return false
      }
      this.mobileErrMsg = ''
      if (this.code === '') {
        this.codeErrMsg = '请输入正确验证码'
        return false
      }
      this.codeErrMsg = ''
      return true
    }

  }
}
</script>

<style lang='scss' scoped>
.btn-wrap{
  padding:20px;
  .van-button{
  width: 100%;
  color: #fff;
  border-radius: 5px;
}
}
</style>
